// PasswordEncoder.js
import CryptoJS from 'crypto-js';

class PasswordEncoder {
  constructor(salt, algorithm) {
    this.salt = salt;
    this.algorithm = algorithm.toUpperCase(); // 确保算法名称是大写
  }

  // 对原始密码进行编码
  encode(rawPass) {
    try {
      const mergedPasswordAndSalt = this.mergePasswordAndSalt(rawPass);
      if (this.algorithm === 'MD5') {
        return CryptoJS.MD5(mergedPasswordAndSalt).toString(CryptoJS.enc.Hex);
      } else if (this.algorithm === 'SHA1') {
        return CryptoJS.SHA1(mergedPasswordAndSalt).toString(CryptoJS.enc.Hex);
      } else if (this.algorithm === 'SHA256') {
        return CryptoJS.SHA256(mergedPasswordAndSalt).toString(CryptoJS.enc.Hex);
      } else if (this.algorithm === 'SHA512') {
        return CryptoJS.SHA512(mergedPasswordAndSalt).toString(CryptoJS.enc.Hex);
      } else {
        throw new Error('Unsupported algorithm');
      }
    } catch (e) {
      console.error(e);
      return null;
    }
  }

  // 检查密码是否有效
  isPasswordValid(encPass, rawPass) {
    const pass1 = encPass;
    const pass2 = this.encode(rawPass);
    return pass1 === pass2;
  }

  // 将密码和盐值合并
  mergePasswordAndSalt(password) {
    if (!password) {
      password = '';
    }

    return this.salt ? `${password}{${this.salt}}` : password;
  }
}

export default PasswordEncoder;
